<template>
  <view class="add-word-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <button class="btn-back" @click="goBack">
        <uni-icon type="left" size="18" color="#333"></uni-icon>
      </button>
      <text class="title">添加单词</text>
      <button class="btn-save" @click="saveWord">
        <text>保存</text>
      </button>
    </view>

    <!-- 表单内容 -->
    <form class="word-form" @submit.prevent="saveWord">
      <!-- 单词输入 -->
      <view class="form-group">
        <text class="form-label required">单词</text>
        <input 
          type="text" 
          v-model="wordForm.content" 
          placeholder="请输入单词" 
          class="form-input"
          maxlength="50"
          focus
        />
      </view>

      <!-- 音标输入 -->
      <view class="form-group">
        <text class="form-label">音标</text>
        <input 
          type="text" 
          v-model="wordForm.phonetic" 
          placeholder="请输入音标（如 /həˈloʊ/）" 
          class="form-input"
          maxlength="100"
        />
      </view>

      <!-- 词义列表 -->
      <view class="form-group">
        <text class="form-label required">词义</text>
        <text class="form-tip">点击"+"添加新词义</text>
        
        <view class="meanings-list">
          <view 
            class="meaning-item" 
            v-for="(meaning, index) in wordForm.meanings" 
            :key="index"
          >
            <view class="meaning-header">
              <text class="meaning-index">词义 {{ index + 1 }}</text>
              <button 
                class="btn-remove-meaning" 
                @click="removeMeaning(index)"
                v-if="wordForm.meanings.length > 1"
              >
                <uni-icon type="trash" size="16" color="#e64340"></uni-icon>
              </button>
            </view>
            
            <!-- 词性选择 -->
            <view class="meaning-fields">
              <view class="pos-input">
                <text class="pos-label">词性</text>
                <picker mode="selector" :range="partsOfSpeech" @change="handlePosChange(index, $event)">
                  <view class="pos-picker">
                    <text>{{ meaning.partOfSpeech || '请选择词性' }}</text>
                    <uni-icon type="arrow-down" size="14" color="#999"></uni-icon>
                  </view>
                </picker>
              </view>
              
              <!-- 释义输入 -->
              <view class="definition-input">
                <text class="definition-label">释义</text>
                <textarea 
                  v-model="meaning.definition" 
                  placeholder="请输入释义" 
                  class="definition-textarea"
                  rows="2"
                  maxlength="200"
                ></textarea>
              </view>
              
              <!-- 例句输入 -->
              <view class="examples-section">
                <text class="examples-label">例句（选填）</text>
                <view class="examples-list">
                  <view 
                    class="example-item" 
                    v-for="(example, exIndex) in meaning.examples" 
                    :key="exIndex"
                  >
                    <input 
                      type="text" 
                      v-model="meaning.examples[exIndex]" 
                      placeholder="请输入例句" 
                      class="example-input"
                      maxlength="300"
                    />
                    <button 
                      class="btn-remove-example" 
                      @click="removeExample(index, exIndex)"
                      v-if="meaning.examples.length > 1"
                    >
                      <uni-icon type="clear" size="16" color="#999"></uni-icon>
                    </button>
                  </view>
                  <button class="btn-add-example" @click="addExample(index)">
                    <uni-icon type="plus" size="14" color="#1989fa"></uni-icon>
                    <text>添加例句</text>
                  </button>
                </view>
              </view>
            </view>
          </view>
          
          <button class="btn-add-meaning" @click="addMeaning">
            <uni-icon type="plus" size="16" color="#1989fa"></uni-icon>
            <text>添加新词义</text>
          </button>
        </view>
      </view>

      <!-- 单词集选择 -->
      <view class="form-group">
        <text class="form-label">单词集</text>
        <picker mode="selector" :range="wordSets" @change="handleWordSetChange">
          <view class="wordset-picker">
            <text>{{ wordForm.wordSet || '请选择单词集' }}</text>
            <uni-icon type="arrow-down" size="14" color="#999"></uni-icon>
          </view>
        </picker>
      </view>

      <!-- 收藏选项 -->
      <view class="form-group">
        <view class="favorite-option">
          <text class="favorite-label">收藏单词</text>
          <uni-switch 
            v-model="wordForm.isFavorite" 
            color="#ffb400"
          ></uni-switch>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="form-actions">
        <button type="submit" class="btn-primary" :disabled="isSubmitting">
          {{ isSubmitting ? '保存中...' : '保存单词' }}
        </button>
      </view>
    </form>
  </view>
</template>

<script>
import { ref, reactive } from 'vue'

export default {
  name: 'AddWord',
  components: {
    uniSwitch: uni.Switch
  },
  setup() {
    
    // 状态管理
    const isSubmitting = ref(false)
    const wordSets = ref(['基础词汇', '进阶词汇', '专业词汇', '常用短语', '新增单词集'])
    const partsOfSpeech = ['n.', 'v.', 'adj.', 'adv.', 'prep.', 'pron.', 'conj.', 'interj.', 'num.', 'art.']
    
    // 表单数据
    const wordForm = reactive({
      content: '',
      phonetic: '',
      meanings: [
        {
          partOfSpeech: '',
          definition: '',
          examples: ['']
        }
      ],
      wordSet: '',
      isFavorite: false
    })
    
    // 验证表单
    const validateForm = () => {
      if (!wordForm.content.trim()) {
        uni.showToast({ title: '请输入单词', icon: 'none' })
        return false
      }
      
      // 验证每个词义
      for (let i = 0; i < wordForm.meanings.length; i++) {
        const meaning = wordForm.meanings[i]
        
        if (!meaning.partOfSpeech) {
          uni.showToast({ title: `请选择第 ${i + 1} 个词义的词性`, icon: 'none' })
          return false
        }
        
        if (!meaning.definition.trim()) {
          uni.showToast({ title: `请输入第 ${i + 1} 个词义的释义`, icon: 'none' })
          return false
        }
      }
      
      return true
    }
    
    // 保存单词
    const saveWord = async () => {
      if (!validateForm()) return
      
      isSubmitting.value = true
      try {
        // 准备提交数据
        const submitData = {
          ...wordForm,
          // 过滤空的例句
          meanings: wordForm.meanings.map(meaning => ({
            ...meaning,
            examples: meaning.examples.filter(example => example.trim())
          }))
        }
        
        // 实际项目中应调用API保存数据
        // await wordAPI.createWord(submitData)
        
        // 模拟API调用
        console.log('添加单词数据:', submitData)
        
        // 显示成功提示
        uni.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            // 成功后返回单词列表页
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        })
      } catch (error) {
        console.error('添加单词失败:', error)
        uni.showToast({ title: '保存失败，请重试', icon: 'none' })
      } finally {
        isSubmitting.value = false
      }
    }
    
    // 添加词义
    const addMeaning = () => {
      wordForm.meanings.push({
        partOfSpeech: '',
        definition: '',
        examples: ['']
      })
    }
    
    // 删除词义
    const removeMeaning = (index) => {
      wordForm.meanings.splice(index, 1)
    }
    
    // 处理词性选择
    const handlePosChange = (meaningIndex, event) => {
      const posIndex = event.detail.value
      wordForm.meanings[meaningIndex].partOfSpeech = partsOfSpeech[posIndex]
    }
    
    // 添加例句
    const addExample = (meaningIndex) => {
      wordForm.meanings[meaningIndex].examples.push('')
    }
    
    // 删除例句
    const removeExample = (meaningIndex, exampleIndex) => {
      wordForm.meanings[meaningIndex].examples.splice(exampleIndex, 1)
    }
    
    // 处理单词集选择
    const handleWordSetChange = (event) => {
      const wordSetIndex = event.detail.value
      const selectedWordSet = wordSets.value[wordSetIndex]
      
      if (selectedWordSet === '新增单词集') {
        // 弹出输入框让用户输入新的单词集名称
        uni.showModal({
          title: '新增单词集',
          content: '请输入新的单词集名称',
          editable: true,
          placeholderText: '单词集名称',
          success: (res) => {
            if (res.confirm && res.content.trim()) {
              // 添加新的单词集到列表
              wordSets.value.splice(wordSets.value.length - 1, 0, res.content.trim())
              wordForm.wordSet = res.content.trim()
            }
          }
        })
      } else {
        wordForm.wordSet = selectedWordSet
      }
    }
    
    // 返回上一页
    const goBack = () => {
      // 检查是否有未保存的更改
      if (hasUnsavedChanges()) {
        uni.showModal({
          title: '提示',
          content: '您有未保存的更改，确定要离开吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack()
            }
          }
        })
      } else {
        uni.navigateBack()
      }
    }
    
    // 检查是否有未保存的更改
    const hasUnsavedChanges = () => {
      // 简单检查
      return wordForm.content.trim() !== '' ||
             wordForm.phonetic.trim() !== '' ||
             wordForm.meanings.some(meaning => 
               meaning.partOfSpeech !== '' || 
               meaning.definition.trim() !== '' ||
               meaning.examples.some(example => example.trim() !== '')
             ) ||
             wordForm.wordSet.trim() !== '' ||
             wordForm.isFavorite
    }
    
    return {
      isSubmitting,
      wordForm,
      wordSets,
      partsOfSpeech,
      saveWord,
      addMeaning,
      removeMeaning,
      handlePosChange,
      addExample,
      removeExample,
      handleWordSetChange,
      goBack
    }
  }
}
</script>

<style scoped>
.add-word-container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.btn-back {
  background: none;
  border: none;
  padding: 8px;
}

.btn-save {
  background: none;
  border: none;
  color: #1989fa;
  font-size: 16px;
}

.word-form {
  padding: 20px;
  background-color: #fff;
}

.form-group {
  margin-bottom: 24px;
}

.form-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.form-label.required::after {
  content: '*';
  color: #e64340;
  margin-left: 4px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-bottom: 12px;
  display: block;
}

.form-input {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 14px;
}

.form-input:focus {
  border-color: #1989fa;
  outline: none;
}

.meanings-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.meaning-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.meaning-item:last-child {
  border-bottom: none;
}

.meaning-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.meaning-index {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.btn-remove-meaning {
  background: none;
  border: none;
  padding: 4px;
}

.meaning-fields {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pos-input, .definition-input, .examples-section {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.pos-label, .definition-label, .examples-label {
  font-size: 13px;
  color: #666;
}

.pos-picker {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.definition-textarea {
  width: 100%;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  min-height: 60px;
  resize: none;
}

.definition-textarea:focus {
  border-color: #1989fa;
  outline: none;
}

.examples-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.example-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.example-input {
  flex: 1;
  height: 36px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  font-size: 14px;
}

.example-input:focus {
  border-color: #1989fa;
  outline: none;
}

.btn-remove-example {
  background: none;
  border: none;
  padding: 4px;
}

.btn-add-example, .btn-add-meaning {
  width: 100%;
  background-color: #f5f5f5;
  border: 1px dashed #ddd;
  border-radius: 6px;
  padding: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
  color: #1989fa;
  font-size: 14px;
}

.wordset-picker {
  width: 100%;
  height: 44px;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 0 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.favorite-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.favorite-label {
  font-size: 14px;
  color: #333;
}

.form-actions {
  margin-top: 32px;
}

.btn-primary {
  width: 100%;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 12px;
  font-size: 16px;
}

.btn-primary:disabled {
  background-color: #ccc;
  color: #fff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .meaning-fields {
    gap: 8px;
  }
  
  .pos-input, .definition-input, .examples-section {
    gap: 4px;
  }
}
</style>